# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from scrapy.utils.project import get_project_settings

from gkfstj.items import SchoolInfoItem, SpecialPlayItem, ProvinceScoreItem, SpecialScoreItem


class GkfstjPipeline(object):
    def __init__(self):
        settings = get_project_settings()
        port = settings['MONGODB_PORT']
        host = settings['MONGODB_HOST']
        db_name = settings['MONGODB_DBNAME']
        client = pymongo.MongoClient(host=host, port=port)
        db = client[db_name]
        self.school_info_sheet = db[settings['MONGODB_TABNAME']]
        self.plan_sheet = db[settings['MONGODB_PLANNAME']]
        self.province_score_sheet = db[settings['MONGODB_PROVINCESCORENAME']]
        self.special_score_sheet = db[settings['MONGODB_SPECIALSCORENAME']]

    def process_item(self, item, spider):
        data = dict(item)
        if isinstance(item, SchoolInfoItem):
            self.school_info_sheet.insert(data)
        if isinstance(item, SpecialPlayItem):
            self.plan_sheet.insert(data.get('special_plan'))
        if isinstance(item, ProvinceScoreItem):
            self.province_score_sheet.insert(data.get('province_score'))
        if isinstance(item, SpecialScoreItem):
            self.special_score_sheet.insert(data.get('special_score'))
        return item
